#include "../netfwd.h"

uint32_t addr_2_busnum( char * os_addr )
{
	uint32_t left_shift[] = { 0, 4, 8 };
	uint32_t bus_addr = 0;
	uint32_t index = 0;
	char * pos = NULL;
	while( NULL != ( pos = strchr( os_addr, '.' ) ) &&
            index < 3 )
	{
		os_addr[pos-os_addr] = 0;
		bus_addr |= strtol( os_addr, NULL, 10 ) << left_shift[index++];
		os_addr = pos+1;
	}
	uint16_t ip4 = strtol( os_addr, NULL, 10 );
	ip4 = ( ip4 << 8 | ip4 >> 8 );
	bus_addr |= uint32_t(ip4 << 16);
	return bus_addr;
}

const char * busnum_2_addr( uint32_t busnum )
{
	static char addr[16] = {0};
	memset( addr, 0, sizeof( addr ) );
	uint32_t ip1 = busnum & 0x0f;
	uint32_t ip2 = ( busnum & 0xf0 ) >> 4;
	uint32_t ip3 = ( busnum & 0xff00 ) >> 8;
	uint16_t ip4 = ( busnum & 0xffff0000 ) >> 16;
	snprintf( addr, 16, "%u.%u.%u.%u", ip1, ip2, ip3, uint16_t(ip4 << 8 | ip4 >> 8) );
	return (const char*)addr;
}

int32_t main( uint32_t argc, char * argv[] )
{
	char os_addr1[] = "1.1.5.158";
	char os_addr2[] = "1.3.2.158";
	char os_addr3[] = "15.15.255.65535";
	
	uint32_t n_os_addr1 = addr_2_busnum( os_addr1 );
	uint32_t n_os_addr2 = addr_2_busnum( os_addr2 );
	uint32_t n_os_addr3 = addr_2_busnum( os_addr3 );
	
	fprintf( stderr, "addr_num1=%u businessid=%u addr_name1=%s\n", n_os_addr1, (( n_os_addr1 >> 8 ) & 0x000000ff ), busnum_2_addr( n_os_addr1 ) );
	fprintf( stderr, "addr_num2=%u businessid=%u addr_name2=%s\n", n_os_addr2, (( n_os_addr2 >> 8 ) & 0x000000ff ), busnum_2_addr( n_os_addr2 ) );
	fprintf( stderr, "addr_num3=%u businessid=%u addr_name3=%s\n", n_os_addr3, (( n_os_addr3 >> 8 ) & 0x000000ff ), busnum_2_addr( n_os_addr3 ) );
	
	fprintf( stderr, "2650801425 addr=%s\n", busnum_2_addr( 2650801425 ) );
	return 0;
}
